package com.ailk.aee.pcc.dao;

import com.ailk.aee.pcc.mongo.Mongo;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 用户业务状态数据存取
 * created at 2014/12/25
 *
 * @author Yiding
 */
@Component
public class UserStatusDao {

    public static final String DATE_FORMAT = "yyyyMMddHHmmss";

    Mongo userStatusMongo;

    /**
     * 保存用户业务状态，参数参考
     * {@link com.ailk.aee.pcc.server.UserStatusServer#saveUserStatus(String, String, String, Date, Date, boolean, String)}
     */
    public void saveUserStatus(
            String userId, String busiType, String busiCode,
            Date startDate, Date endDate, boolean validFlag, String tradeId) {

        DBCollection collection = userStatusMongo.getContentCollection();
        String fieldName = busiType + "$" + busiCode;

        // 如果已经被增量更新过，则跳过该属性
        if (isIncrementUpdated(collection, userId, fieldName)) {
            return;
        }

        // 更新属性值
        BasicDBObject status = new BasicDBObject()
                .append("start_date", formatDate(startDate))
                .append("end_date", formatDate(endDate))
                .append("vaild_flag", String.valueOf(validFlag));

        BasicDBObject update = new BasicDBObject("$set", new BasicDBObject(fieldName, status));
        collection.update(new BasicDBObject("userId", userId), update, true, false);
    }

    /**
     * 增量保存用户业务状态，参数参考
     * {@link com.ailk.aee.pcc.server.UserStatusServer#saveUserStatus(String, String, String, Date, Date, boolean, String)}
     * 增量保存的记录需要添加一个 :incrementUpdated 属性，以避免被全量同步覆盖
     */
    public void saveUserStatusIncr(
            String userId, String busiType, String busiCode,
            Date startDate, Date endDate, boolean validFlag, String tradeId) {

        DBCollection collection = userStatusMongo.getContentCollection();
        String fieldName = busiType + "$" + busiCode;
        String fieldNameIncr = busiType + "$" + busiCode + ":incrementUpdated";

        // 更新属性值
        BasicDBObject status = new BasicDBObject()
                .append("start_date", formatDate(startDate))
                .append("end_date", formatDate(endDate))
                .append("vaild_flag", String.valueOf(validFlag));

        BasicDBObject update = new BasicDBObject("$set",
                new BasicDBObject(fieldName, status).append(fieldNameIncr, true)
        );
        collection.update(new BasicDBObject("userId", userId), update, true, false);
    }

    /**
     * 判断指定用户的指定属性是否已经被增量更新过了。如果已经被增量更新过，则不需要
     * 再全量更新，全量更新的数据应该忽略掉，不可以覆盖增量更新的数据。
     *
     * @param collection 集合
     * @param userId     用户ID
     * @param fieldName  属性名称
     * @return 该属性是否已经被增量更新过
     */
    private boolean isIncrementUpdated(DBCollection collection, String userId, String fieldName) {
        BasicDBObject query = new BasicDBObject("userId", userId);
        DBObject row = collection.findOne(query, new BasicDBObject(fieldName + ":incrementUpdated", 1));

        return row != null && row.get("incrementUpdated") != null;
    }

    private String formatDate(Date startDate) {
        return DateFormatUtils.format(startDate, DATE_FORMAT);
    }
}
